package dao

import (
	"daily-blog/global"
	"daily-blog/model"
)

func CreatePost(post *model.Post) error {
	return global.GVA_DB.Model(&model.Post{}).Create(post).Error
}
func DeletePostByID(id string) error {
	return global.GVA_DB.Delete(&model.Post{}, "post_id = ?", id).Error
}
func GetPostByID(id string) (postContent string, err error) {
	if err = global.GVA_DB.Model(&model.Post{}).Select([]string{"content"}).
		First(&postContent, "post_id = ?", id).Error; err != nil {
		return "", err
	}
	return
}
func UpdatePost(post *model.Post) error {
	return global.GVA_DB.Model(post).Where("post_id=?", post.PostId).Updates(*post).Error
}
func GetPostList() (posts []model.PostWithoutContent, err error) {
	err = global.GVA_DB.Model(&model.Post{}).
		Select([]string{"post_id", "title", "desc", "content", "author", "category_id", "category_name", "created_at"}).
		Find(&posts).Error
	if err != nil {
		return nil, err
	}
	return
}

// GetPostListByCategoryId 获取目录下的所有文章
func GetPostListByCategoryId(categoryId string) ([]model.PostWithoutContent, error) {
	var posts []model.PostWithoutContent
	err := global.GVA_DB.Model(&model.Post{}).
		Select([]string{"post_id", "title", "desc", "author", "category_id", "category_name", "created_at"}).
		Find(&posts, "category_id=?", categoryId).Error
	return posts, err
}

// GetPostIDListByTagId 获取标签相关的所有文章Id
func GetPostIDListByTagId(tagId string) ([]string, error) {
	var postIds []string
	err := global.GVA_DB.Model(&model.PostTag{}).
		Select("post_id").
		Find(&postIds, "tag_id=?", tagId).Error
	return postIds, err
}

// GetPostListByIds 获取文章列表通过ids
func GetPostListByIds(postIds []string) (postList []model.PostWithoutContent, err error) {
	// select ,,, from post where post_id in postIds
	err = global.GVA_DB.Model(&model.Post{}).
		Select([]string{"post_id", "title", "desc", "author", "category_id", "category_name", "created_at"}).
		Find(&postList, "post_id in ?", postIds).Error
	return
}

// GetPostTagsByPostIds 查找指定文章的标签
func GetPostTagsByPostIds(postIds []string) (postTags []model.PostTag, err error) {
	err = global.GVA_DB.Model(&model.PostTag{}).Select("post_id", "tag_id", "tag_name").
		Where("post_id in ?", postIds).
		Find(&postTags).Error
	return
}
